package nanhua.spring_aop.aop;


import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Slf4j
@Aspect
@Component
public class MyAspect {


    @Before("@annotation(nanhua.spring_aop.aop.OrderAnnotiation)")
    public void before()
    {
        System.out.println("hello，我是一个前置增强");
    }

    @Around("@annotation(nanhua.spring_aop.aop.OrderAnnotiation)")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {

        // 权限检查
        if (!checkPermission()) {
            System.out.println("由于权限不足，操作被终止");
            return null; // 或者根据方法返回类型返回适当的默认值
        }

        long begin = System.currentTimeMillis();

        Object result = pjp.proceed();

        long end = System.currentTimeMillis();
        //耗时
        log.info("该方法共耗时：{}", end - begin);

        //返回值
        System.out.println("Method " + pjp.getSignature().getName() +
                " returned: " + result);
        return result;
    }



    @After("@annotation(nanhua.spring_aop.aop.OrderAnnotiation)")
    public void after()
    {
        System.out.println("bye，我是一个后置增强");
    }


    //检查权限
    public boolean checkPermission() {
        int random = (int) (Math.random() * 2); // 随机生成 0 或 1
        if (random == 1) {
            System.out.println("权限不足，无法执行操作！");
            return false;
        }
        System.out.println("权限验证通过，可以执行操作。");
        return true;
    }

}
